//
//  LCUploadFilesListVC.m
//  LongChain
//
//  Created by fengzi on 2018/6/19.
//  Copyright © 2018年 FengZi. All rights reserved.
//

#import "LCUploadFilesListVC.h"
#import "LCUploadFileCell.h"

#import <Photos/Photos.h>

@interface LCUploadFilesListVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UIButton *localFileButton;
@property (weak, nonatomic) IBOutlet UIButton *allFilesButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineViewCenterX;


@property (weak, nonatomic) IBOutlet UICollectionView *uploadFileList;


@property (nonatomic, strong) NSArray *listDatas;


@end

@implementation LCUploadFilesListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = (self.uploadFileType == 1) ? @"选择图片" : @"选择视频";
    [self loadLocalImages];
}

- (void)loadLocalImages {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        switch (status) {
            case PHAuthorizationStatusAuthorized:
            {
                NSLog(@"通过");
                
                [self achievePhoto];
            }
                break;
            default:
            {
                NSLog(@"不通过");
            }
                break;
        }
    }];

}

- (void)achievePhoto {
    

    switch (self.uploadFileType) {
        case UploadFilesTypeImage:
        {
            // 获得相机胶卷
            PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
            [self enumerateAssetsInAssetCollection:cameraRoll original:NO];

        }
            break;
        case UploadFilesTypeVideo:
        {
            // 获得相机胶卷
            PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil].lastObject;
            [self enumerateAssetsInAssetCollection:cameraRoll original:NO];

        }
            break;
            
        default:
            break;
    }
}

- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
{
//    NSLog(@"相簿名:%@", assetCollection.localizedTitle);
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    
    // 获得某个相簿中的所有PHAsset对象
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:0];
    for (PHAsset *asset in assets) {
        // 是否要原图
        CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            [images addObject:result];
//            NSLog(@"%@", result);
        }];
    }
    
    self.listDatas = images;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.uploadFileList reloadData];

    });
}

#pragma mark - -
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];

    LCUploadFileCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"uploadFileCell" forIndexPath:indexPath];
    if (self.listDatas.count > row) {
        [cell updateUploadFileImageWithParameter:self.listDatas[row]];
    }
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.listDatas.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((SWidth - 55) / 4, (SWidth - 55) / 4);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LCLog(@"点击");
    
    NSInteger row = [indexPath row];

    UIImage *image = self.listDatas[row];
    NSDictionary *dic = @{@"dir_id":@(0),@"tag_id":@(0)};
    NSDate *current = [NSDate dateWithTimeIntervalSinceNow:0];

    NSTimeInterval timeInterval = [current timeIntervalSince1970];
    // *1000,是精确到毫秒；这里是精确到秒
    NSString *result = [NSString stringWithFormat:@"%.0f",timeInterval];
    result = [NSString stringWithFormat:@"%@.png",result];
    NSLog(@"current = %@",result);
    
    [[LCNetwork shareInstance]uploadFile:image Path:@"/api/v0/nas/upload" mimeType:@"" name:@"" Name:result parameter:dic successBlock:^(id sender) {
        
        LCLog(@"sender = %@",sender);
        
    } failBlock:^(id sender) {
        LCLog(@"sender = %@",sender);

    }];
    
}

#pragma Mark - -
- (IBAction)selectAllUploadFiles:(id)sender {
    LCLog(@"全选");
}

//  未上传
- (IBAction)localFiles:(UIButton *)sender {
    self.lineViewCenterX.constant = sender.center.x - SWidth / 4;
    [self.localFileButton setTitleColor:RGB(0.0f, 122.0f, 255.0f) forState:UIControlStateNormal];
    [self.allFilesButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    
}

- (IBAction)allFiles:(UIButton *)sender {
    
    self.lineViewCenterX.constant = sender.center.x - SWidth / 4;
    [self.allFilesButton setTitleColor:RGB(0.0f, 122.0f, 255.0f) forState:UIControlStateNormal];
    [self.localFileButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];


}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
